package com.hzz.service.examine;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.hzz.api.examine.IExamineResultAttachService;
import com.hzz.api.examine.IExamineResultDetailService;
import com.hzz.api.examine.IExamineResultService;
import com.hzz.dao.examine.IExamineResultDao;
import com.hzz.dto.analysis.ExamineResultLevelStatDto;
import com.hzz.dto.analysis.ExamineResultRankStatDto;
import com.hzz.dto.examine.ApiExamineResultDto;
import com.hzz.dto.examine.ExamineResultAttachDto;
import com.hzz.dto.examine.ExamineResultDetailDto;
import com.hzz.dto.examine.ExamineResultDto;
import com.hzz.entity.examine.ExamineResult;
import com.hzz.framework.Response;
import com.hzz.framework.SysErrorCode;
import com.hzz.framework.annotation.FeignService;
import com.hzz.framework.exception.ServiceException;
import com.hzz.framework.service.BaseService;
import com.hzz.framework.util.CommonConstant;
import com.hzz.framework.util.DateUtil;
import com.hzz.framework.util.IdUtil;

import lombok.extern.slf4j.Slf4j;

@FeignService
@Slf4j
public class ExamineResultService extends BaseService implements IExamineResultService {
	@Autowired
	IExamineResultDao examineResultDao;
	@Autowired
	IExamineResultDetailService examineResultDetailService;
	@Autowired
	IExamineResultAttachService examineResultAttachService;

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = CommonConstant.DB_DEFAULT_TIMEOUT, rollbackFor = {
			Exception.class, RuntimeException.class })
	public Response saveOrUpdateData(ExamineResultDto dto) throws Exception {
		Response result = new Response(0, "success");
		try {
			ExamineResult entity = copyTo(dto, ExamineResult.class);
			// 判断数据是否存在
			if (examineResultDao.isDataExist(entity) != 0) {
				/**
				 * 更新仅保存自评分时用，只允许执行一次
				 */
				entity.setSelfTime(new Date());// 自评时间
				entity.setTotalScore(entity.getLeaderScore().add(entity.getSelfScore()));
				// 数据存在
				examineResultDao.update(entity);
			} else {
				// 新增
				if (entity.getId() == null) {
					entity.setId(IdUtil.nextId());
				}
				examineResultDao.insert(entity);
				result.data = entity.getId();
			}

			// 保存自评分明细
			if (dto.getResultDetails() != null) {
				for (ExamineResultDetailDto detail : dto.getResultDetails()) {
					examineResultDetailService.saveOrUpdateData(detail);
				}
			}
			// 保存附件
			if (dto.getAttachs() != null) {
				examineResultAttachService.deleteDataByResultId(dto.getId());// 先逻辑删除原有附件
				for (ExamineResultAttachDto attach : dto.getAttachs()) {
					attach.setResultId(dto.getId());
					examineResultAttachService.saveOrUpdateData(attach);
				}
			}
		} catch (Exception e) {
			log.error("信息保存异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return result;
	}

	@Override
	public String deleteData(ExamineResultDto dto) throws Exception {
		String result = "success";
		try {
			ExamineResult entity = copyTo(dto, ExamineResult.class);
			if (examineResultDao.deleteByPrimaryKey(entity) == 0) {
				throw new RuntimeException("数据不存在!");
			}
		} catch (Exception e) {
			log.error("物理删除异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return result;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = CommonConstant.DB_DEFAULT_TIMEOUT, rollbackFor = {
			Exception.class, RuntimeException.class })
	public String deleteDataById(ExamineResultDto dto) throws Exception {
		String result = "success";
		try {
			ExamineResult entity = copyTo(dto, ExamineResult.class);
			if (examineResultDao.deleteById(entity) == 0) {
				throw new RuntimeException("数据不存在!");
			}
		} catch (Exception e) {
			log.error("逻辑删除异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return result;
	}

	@Override
	public PageInfo findDataIsPage(ExamineResultDto dto) throws Exception {
		PageInfo pageInfo = null;
		try {
			ExamineResult entity = copyTo(dto, ExamineResult.class);
			PageHelper.startPage(PN(dto.getPageNum()), PS(dto.getPageSize()));
			List list = examineResultDao.findDataIsPage(entity);
			pageInfo = new PageInfo(list);
			pageInfo.setList(copyTo(pageInfo.getList(), ExamineResultDto.class));
		} catch (Exception e) {
			log.error("信息[分页]查询异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return pageInfo;
	}

	@Override
	public List<ExamineResultDto> findDataIsList(ExamineResultDto dto) throws Exception {
		List<ExamineResultDto> results = null;
		try {
			ExamineResult entity = copyTo(dto, ExamineResult.class);
			results = copyTo(examineResultDao.findDataIsList(entity), ExamineResultDto.class);
		} catch (Exception e) {
			log.error("信息[列表]查询异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return results;
	}

	@Override
	public ExamineResultDto findDataById(ExamineResultDto dto) throws Exception {
		ExamineResultDto result = null;
		try {
			ExamineResult entity = copyTo(dto, ExamineResult.class);
			result = copyTo(examineResultDao.selectByPrimaryKey(entity), ExamineResultDto.class);
		} catch (Exception e) {
			log.error("信息[详情]查询异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return result;
	}

	@Override
	public PageInfo findJuniorDataIsPage(ExamineResultDto dto) throws Exception {
		PageInfo pageInfo = null;
		try {
			PageHelper.startPage(PN(dto.getPageNum()), PS(dto.getPageSize()));
			List list = examineResultDao.findJuniorDataIsPage(dto);
			pageInfo = new PageInfo(list);
			pageInfo.setList(pageInfo.getList());
		} catch (Exception e) {
			log.error("信息[分页]查询异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return pageInfo;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = CommonConstant.DB_DEFAULT_TIMEOUT, rollbackFor = {
			Exception.class, RuntimeException.class })
	public Response updateLeaderScore(ExamineResultDto dto) throws Exception {
		Response result = new Response(0, "success");
		try {
			dto.setLeaderTime(new Date());
			ExamineResult entity = copyTo(dto, ExamineResult.class);
			ExamineResult oldEntity = (ExamineResult) examineResultDao.selectByPrimaryKey(entity);
			entity.setTotalScore(entity.getLeaderScore().add(oldEntity.getSelfScore()));

			examineResultDao.update(entity);
		} catch (Exception e) {
			log.error("信息保存异常!", e);
			throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
		}
		return result;
	}

	@Override
	public List<ApiExamineResultDto> findDataForApp(ExamineResultDto dto) {
		return examineResultDao.findDataForApp(dto);
	}

	@Override
	public List<ExamineResultRankStatDto> statResultRankByParentAreaId(ExamineResultRankStatDto dto) {
		// 按年份获取考核排名结果
		Integer startYear = dto.getStartYear();
		Integer endYear = dto.getEndYear();
		if (dto.getStartYear() == null && dto.getEndYear() == null) {
			startYear = DateUtil.getLastYear();
			endYear = startYear;
		}

		List<ExamineResultRankStatDto> newList = new ArrayList<>();
		for (int i = startYear; i <= endYear; i++) {
			dto.setYear(i);
			List<ExamineResultRankStatDto> list = examineResultDao.statResultRankByParentAreaId(dto);
			if (list != null) {
				// 将结果集按图表要求重新生成
				for (ExamineResultRankStatDto obj : list) {
					ExamineResultRankStatDto temp = null;
					// 从新集合中查找行政区划数据
					for (ExamineResultRankStatDto newObj : newList) {
						if (newObj.getName().equals(obj.getName())) {
							temp = newObj;
							break;
						}
					}
					// 如果分值小于0，排名设置为0
					int rank = obj.getScore().compareTo(new BigDecimal("0")) < 0 ? 0 : obj.getRank();

					if (temp == null) {// 不存在，新增对象
						temp = new ExamineResultRankStatDto();
						temp.setName(obj.getName());
						temp.addDetail(obj.getYear(), obj.getScore(), rank);
						newList.add(temp);
					} else {// 已存在，追加明细
						temp.addDetail(obj.getYear(), obj.getScore(), rank);
					}
				}
			}
		}

		return newList;
	}

	@Override
	public List<ExamineResultLevelStatDto> statResultLevelByParentAreaId(ExamineResultLevelStatDto dto) {
		return examineResultDao.statResultLevelByParentAreaId(dto);
	}

	/**
	 * 获取上年度考核前5名和后5名
	 */
	@Override
    public Map<String, BigDecimal> getLastYearRank5(Integer type) {
		Map<String, BigDecimal> result = Maps.newLinkedHashMap();
		List<ExamineResultRankStatDto> list = examineResultDao.getLastYearRank5(type);
		// 将list结果集转换成MAP对象
		if (list != null) {
			for (ExamineResultRankStatDto dto : list) {
				result.put(dto.getName(), dto.getScore());
			}
		}
		return result;
	}
}
